package com.example.radioclub.login;

import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;


import com.example.radioclub.data.Constants;
import com.example.radioclub.login.google.interfaces.IGoogleUserInfoTask;
import com.example.radioclub.login.google.tasks.GoogleUserInfoTask;
import com.example.radioclub.R;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This class wraps things about logging in by using Google account.
 * 
 * @author wizard
 * 
 */
@SuppressWarnings("deprecation")
public class GoogleLoginActivity extends Activity implements IGoogleUserInfoTask{
	private final String TAG = Constants.APP_TAG + "Google Login Activity";
	private final int DIALOG_ACCOUNT = new String("dialog_account").hashCode();
	private final String AUTH_TOKEN_TYPE = Constants.GOOGLE_API_AUTH_TYPE;
	private GoogleUserInfoTask googleUserInfoTask;
	private ProgressDialog progressDialog;
	private AccountManager accountManager;
	private Account[] accounts;
	private Account account;
	private String chosenEmail = null;
	private AlertDialog alertDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.activity_main_page);
		Log.i(TAG, "onCreate() is called.");
		if(Constants.CLIENT_LOGIN_STATUS == false) {
			this.accountManager = AccountManager.get(this);
			this.accounts = this.accountManager.getAccountsByType("com.google");
			if(Constants.CLIENT_LOGIN_STATUS == false) {
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle("Select Google Account");
				final Account[] accounts = this.accounts;
				final int size = accounts.length;
				String[] names = new String[size];
				for(int i=0; i<size; ++i) {
					names[i] = accounts[i].name;
				}
				builder.setItems(names, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(final DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						chosenEmail = accounts[which].name;
						accountManager.getAuthToken(accounts[which], 
							AUTH_TOKEN_TYPE, null, GoogleLoginActivity.this, 
							new AccountManagerCallback<Bundle>() {
								
								@Override
								public void run(AccountManagerFuture<Bundle> future) {
									// TODO Auto-generated method stub
									try {
										String token = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
										if(token != null) {
											Log.i(TAG, "Using local token = " + token);
											googleUserInfoTask = new GoogleUserInfoTask(token, GoogleLoginActivity.this);
											googleUserInfoTask.execute();
											progressDialog = ProgressDialog.show(GoogleLoginActivity.this, "Please wait.", "Acquiring User Info.");
										}
									} catch (OperationCanceledException e) {
										Log.i(TAG, e.getMessage());
									} catch (AuthenticatorException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}
							}, null);
					}
				});
				alertDialog = builder.create();
				alertDialog.show();
			}
		} else {
			Log.i(TAG, "Already logged in. Please log out if you want to use another account.");
		}
	}
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
	}
	
		
	@Override
	public void onUserInfoAcquired(String result) {
		// TODO Auto-generated method stub
		if(this.alertDialog.isShowing()) this.alertDialog.dismiss();
		if(this.progressDialog.isShowing()) this.progressDialog.dismiss();
		if(result == null) {
			Log.i(TAG, "No user info acquired. Please try again later.");
			Toast.makeText(this, "No user info acquired. Please try again later.", Toast.LENGTH_SHORT).show();
			return;
		}
		
		String id = null, name = null, link = null, picture = null;
		JSONObject userInfo;
		try {
			userInfo = new JSONObject(result);
			id = userInfo.getString("id");
			name = userInfo.getString("name");
			link = userInfo.getString("link");
			if(userInfo.has("picture")) {
				picture = userInfo.getString("picture");
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Bundle bundle = new Bundle();
		bundle.putString("id", id);
		bundle.putString("name", name);
		bundle.putString("email", chosenEmail);
		bundle.putString("link", link);
		bundle.putString("picture", picture);
		bundle.putInt("login", Constants.GOOGLE_LOGIN);
		Constants.CLIENT_LOGIN_STATUS = true;
		this.setResult(RESULT_OK, new Intent().putExtras(bundle));
		this.finish();
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		Log.i(TAG, "onResume() is called.");
		super.onResume();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		Log.i(TAG, "onActivityResult() is called.");
		super.onActivityResult(requestCode, resultCode, data);
	}
}
